﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace Daphne.ControlsMetro.Clock
{
    /// <summary>
    /// Class representing digital clock control
    /// </summary>
    public sealed partial class DigitalClock : UserControl
    {
        /// <summary>
        /// Dependency Property for time to show
        /// </summary>
        public static readonly DependencyProperty TimeProperty;

        /// <summary>
        /// Register dependency properties
        /// </summary>
        static DigitalClock()
        {
            TimeProperty = DependencyProperty.Register("Time", typeof(TimeSpan), typeof(DigitalClock),
                                        new PropertyMetadata(TimeSpan.FromMilliseconds(0), OnTimeValueChanged ));
        }

        /// <summary>
        /// Handler registering the time change
        /// </summary>
        static void OnTimeValueChanged(DependencyObject depObject, DependencyPropertyChangedEventArgs args)
        {
            (depObject as DigitalClock).UpdateTime();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public DigitalClock()
        {
            this.InitializeComponent();

            this.Loaded += DigitalClock_Loaded;
        }

        /// <summary>
        /// Loaded handler to set initial clock display
        /// </summary>
        void DigitalClock_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateTime();
        }

        /// <summary>
        /// CLR Wrapper for Time dependency property
        /// </summary>
        public TimeSpan Time
        {
            get
            {
                return (TimeSpan)GetValue(TimeProperty);
            }
            set
            {
                SetValue(TimeProperty, value);
            }
        }

        /// <summary>
        /// Sets the new time value
        /// </summary>
        private void UpdateTime()
        {
            // get time values
            TimeSpan timeSpan = Time;
            int minutes = Convert.ToInt32(Math.Floor(timeSpan.TotalMinutes));
            int seconds = timeSpan.Seconds;

            // set time values to digital numbers
            uxMinutesFirst.Number = (minutes / 10) % 10;
            uxMinutesSecond.Number = minutes % 10;
            uxSecondsFirst.Number = seconds / 10;
            uxSecondsSecond.Number = seconds % 10;          
        }
    }
}
